package pl.factat.gfk;

import java.awt.image.BufferedImage;

/**
 * Created with IntelliJ IDEA.
 * User: adam
 * Date: 08.01.13
 * Time: 19:03
 * Abstract image processor class. Contains a method for bilinear interpolation.
 */
abstract class ImageProcessor {
    abstract public BufferedImage process(BufferedImage img);

    /**
     * Does a bilinear interpolation on ARGB values.
     *
     * @param xw x-weight (out_width/src_width), values from range [0.0; 1.0]
     * @param yw x-weight (out_height/src_height), values from range [0.0; 1.0]
     * @param nw North-West point RGB values.
     * @param ne North-East point RGB values.
     * @param sw South-West point RGB values.
     * @param se South-East point RGB values.
     * @return Interpolated RGB values.
     */
    protected RGBPoint bilinearInterpolation(double xw, double yw, RGBPoint nw, RGBPoint ne, RGBPoint sw, RGBPoint se) {
        double m0, m1;
        int a0 = nw.a;
        int r0 = nw.r;
        int g0 = nw.g;
        int b0 = nw.b;
        int a1 = ne.a;
        int r1 = ne.r;
        int g1 = ne.g;
        int b1 = ne.b;
        int a2 = sw.a;
        int r2 = sw.r;
        int g2 = sw.g;
        int b2 = sw.b;
        int a3 = se.a;
        int r3 = se.r;
        int g3 = se.g;
        int b3 = se.b;

        double cx = 1.0f - xw;
        double cy = 1.0f - yw;

        m0 = cx * a0 + xw * a1;
        m1 = cx * a2 + xw * a3;
        int a = (int) (cy * m0 + yw * m1);

        m0 = cx * r0 + xw * r1;
        m1 = cx * r2 + xw * r3;
        int r = (int) (cy * m0 + yw * m1);

        m0 = cx * g0 + xw * g1;
        m1 = cx * g2 + xw * g3;
        int g = (int) (cy * m0 + yw * m1);

        m0 = cx * b0 + xw * b1;
        m1 = cx * b2 + xw * b3;
        int b = (int) (cy * m0 + yw * m1);
        RGBPoint out = new RGBPoint();
        out.r = r;
        out.a = a;
        out.b = b;
        out.g = g;
        return out;
    }
}
